package com.aiou.security.authentication.wechat;

import com.aiou.security.properties.SecurityConstants;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zyb
 */
@Getter
@Setter
public class WeChatAuthenticationFilter extends
        AbstractAuthenticationProcessingFilter {
    // ~ Static fields/initializers
    // =====================================================================================


    private String codeParameter = SecurityConstants.DEFAULT_WECHAT_CODE;
    private boolean postOnly = true;

    // ~ Constructors
    // ===================================================================================================

    public WeChatAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.DEFAULT_WECHAT_LOGIN, HttpMethod.POST.name()));
    }

    // ~ Methods
    // ========================================================================================================

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String code = obtainCode(request);

        if (code == null) {
            code = "";
        }

        code = code.trim();


        WeChatAuthenticationToken authRequest = new WeChatAuthenticationToken(code);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }


    protected String obtainCode(HttpServletRequest request) {
        return request.getParameter(codeParameter);
    }



    protected void setDetails(HttpServletRequest request,
                              WeChatAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

}